﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace DarwinIsDead.Weapons {
    class Pistol : Weapon {
        private const int NUM_BULLETS = 4;
        private const float SPREAD = (float)(Math.PI / 20.0);

        private int currentBullet;
        private bool pressed;

        private Random rng;

        public Pistol(World world, bool friendly) :
            base(world,
                 world.Game.Content.Load<Texture2D>("Sprites\\Weapons\\sprPistol"),
                 new Vector2(8f, 16f),
                 18f,
                 friendly) {
            for (int i = 0; i < NUM_BULLETS; i++) {
                Bullet bullet = new Bullets.Linear(World, 3, 1200f, 1000f, friendly);
                Bullets.Add(bullet);
                World.AddEntity(bullet);
            }

            currentBullet = 0;
            pressed = false;
            rng = new Random();
        }

        private void Fire() {
            currentBullet = (currentBullet + 1) % Bullets.Count;

            // Fire the bullet
            Bullet bullet = Bullets[currentBullet];
            if (!bullet.Active) {
                bullet.Position = new Vector2(
                    Position.X + BarrelLength * (float)Math.Cos(Direction),
                    Position.Y + BarrelLength * (float)Math.Sin(Direction));

                float spread = (float)((rng.NextDouble() - 0.5) * 2f) * SPREAD;
                bullet.FireAngle = Direction + spread;
                bullet.Active = true;
                bullet.Solid = true;
            }
        }

        public override void InternalUpdate(GameTime gameTime) {
            MouseState mouseState = Mouse.GetState();

            if (!pressed && mouseState.LeftButton == ButtonState.Pressed) {
                Fire();
                pressed = true;
            } else if (mouseState.LeftButton == ButtonState.Released) {
                pressed = false;
            }
        }
    }
}
